import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class YwqFastMVP extends AnAction {


    private Project project;
    //包名
    private String packageName = "";

    private String mClassname;//类开头
    private String mModuleName;//模块名称
    private boolean activityCheckBoxisSelected;
    private boolean fragmentCheckBoxisSelected;
    private boolean serviceCheckBoxisSelected;
    private boolean repositoryCheckBoxisSelected;
    private boolean apiCheckBoxisSelected;

    private enum CodeType {
        Activity, Fragment, View, Presenter, Service, ServiceImpl, Repository, Api
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        project = e.getData(PlatformDataKeys.PROJECT);
        init();
        refreshProject(e);
    }

    /**
     * 刷新项目
     *
     * @param e
     */
    private void refreshProject(AnActionEvent e) {
        e.getProject().getBaseDir().refresh(false, true);
    }

    /**
     * 初始化Dialog
     */
    private void init() {
        FastMVP myDialog = new FastMVP(new FastMVP.DialogCallBack() {

            @Override
            public void ok(String packageNames, String ClassName, String moduleName, Boolean activity, Boolean fragment, Boolean service, Boolean repository, Boolean api) {
                activityCheckBoxisSelected = activity;
                fragmentCheckBoxisSelected = fragment;
                serviceCheckBoxisSelected = service;
                repositoryCheckBoxisSelected = repository;
                apiCheckBoxisSelected = api;
                mClassname = ClassName;
                mModuleName = moduleName;
                if (packageNames.isEmpty()){
                    packageName = "com." + moduleName.toLowerCase();
                }else {
                    packageName = packageNames;
                }


                createKtFiles();
                Messages.showInfoMessage(project, "哈哈,create mvp code success", "title");
            }
        });
        myDialog.setVisible(true);

    }

    /**
     * 生成Kotlin文件
     */
    private void createKtFiles() {

        createClassFile(CodeType.View);
        createClassFile(CodeType.Presenter);

        if (activityCheckBoxisSelected) {
            createClassFile(CodeType.Activity);
        }


        if (fragmentCheckBoxisSelected) {
            createClassFile(CodeType.Fragment);
        }


        if (serviceCheckBoxisSelected){
            createClassFile(CodeType.ServiceImpl);
            createClassFile(CodeType.Service);
        }
        if (repositoryCheckBoxisSelected) {
            createClassFile(CodeType.Repository);
        }
         if (apiCheckBoxisSelected){
             createClassFile(CodeType.Api);
         }



    }


    /**
     * 生成mvp框架代码
     *
     * @param codeType
     */
    private void createClassFile(CodeType codeType) {
        String fileName = "";
        String content = "";
        String appPath = getAppPath();
        switch (codeType) {
            case Activity:
                fileName = "TemplateActivity.txt";
                content = ReadTemplateFile(fileName);
                content = dealTemplateContent(content);
                writeToFile(content, appPath + "/ui/activity", mClassname + "Activity.kt");
                break;
            case Fragment:
                fileName = "TemplateFragment.txt";
                content = ReadTemplateFile(fileName);
                content = dealTemplateContent(content);
                writeToFile(content, appPath + "/ui/fragment", mClassname + "Fragment.kt");
                break;
            case View:
                fileName = "TemplateView.txt";
                content = ReadTemplateFile(fileName);
                content = dealTemplateContent(content);
                writeToFile(content, appPath + "/presenter/view", mClassname + "View.kt");
                break;
            case Presenter:
                fileName = "TemplatePresenter.txt";
                content = ReadTemplateFile(fileName);
                content = dealTemplateContent(content);
                writeToFile(content, appPath + "/presenter", mClassname + "Presenter.kt");
                //  writeToFile(content, appPath + mClassname.toLowerCase()+"/presenter", mClassname + "Presenter.kt");
                break;


            case Service:
                fileName = "TemplateService.txt";
                content = ReadTemplateFile(fileName);
                content = dealTemplateContent(content);
                writeToFile(content, appPath + "/service", mClassname + "Service.kt");
                break;


            case ServiceImpl:
                fileName = "TemplateServiceImpl.txt";
                content = ReadTemplateFile(fileName);
                content = dealTemplateContent(content);
                writeToFile(content, appPath + "/service/impl", mClassname + "ServiceImpl.kt");
                break;


            case Repository:
                fileName = "TemplateRepository.txt";
                content = ReadTemplateFile(fileName);
                content = dealTemplateContent(content);
                writeToFile(content, appPath + "/data/repository", mClassname + "Repository.kt");
                break;


            case Api:
                fileName = "TemplateApi.txt";
                content = ReadTemplateFile(fileName);
                content = dealTemplateContent(content);
                writeToFile(content, appPath + "/data/api", mClassname + "Api.kt");
                break;


        }
    }

    /**
     * 获取包名文件路径
     *
     * @return
     */
    private String getAppPath() {
        String packagePath = packageName.replace(".", "/");
        String appPath = project.getBasePath() + "/" + mModuleName + "/src/main/java/" + packagePath + "/";
        return appPath;
    }

    /**
     * 替换模板中字符
     *
     * @param content
     * @return
     */
    private String dealTemplateContent(String content) {
        content = content.replace("$name", mClassname);
        if (content.contains("$packagename")) {
            content = content.replace("$packagename", packageName);
        }
    /*    if (content.contains("$basepackagename")){
            content = content.replace("$basepackagename", packageName + ".base");
        }*/
        content = content.replace("$author", "ywq");
        content = content.replace("$date", getDate());
        return content;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public String getDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }


    /**
     * 读取模板文件中的字符内容
     *
     * @param fileName 模板文件名
     * @return
     */
    private String ReadTemplateFile(String fileName) {
        InputStream in = null;
        in = this.getClass().getResourceAsStream("/Template/" + fileName);
        String content = "";
        try {
            content = new String(readStream(in));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }


    private byte[] readStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        try {
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.close();
            inputStream.close();
        }

        return outputStream.toByteArray();
    }


    /**
     * 生成
     *
     * @param content   类中的内容
     * @param classPath 类文件路径
     * @param className 类文件名称
     */
    private void writeToFile(String content, String classPath, String className) {
        try {
            File floder = new File(classPath);
            if (!floder.exists()) {
                floder.mkdirs();
            }

            File file = new File(classPath + "/" + className);
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
